<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Http;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
use think\process\pipes\Windows;
use think\Request;
use think\Response;
use think\response\Json;

/**
 * 订单处理器
 *
 * @icon fa fa-circle-o
 */
class Proccessor extends Backend
{

    /**
     * Tickets模型对象
     * @var \app\admin\model\Proccessor
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Proccessor;
        $this->view->assign("regionList", $this->model->getRegionList());
        $this->view->assign("shopNoList", $this->model->getShopNoList());
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $result = ['total' => 0, 'rows' => []];
        if (false === $this->request->isAjax()) {

            //return         header('Location: http://localsheets.com/67dd4e3aaa734.xlsx',false);

            return $this->view->fetch();
        }

        return json($result);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $region = $this->model->getRegionList()[$params['region']];
        $shopNo = $this->model->getShopNoList()[$params['shop_no']];

        $shopFlag = $shopNo . $region;//A越南

        ini_set("memory_limit", "-1");

        //订单元数据
        $orderSheetsPath = ROOT_PATH . 'public/' . $params['avatar'];
        //结算单
        $orderSettlementSheetsPath = ROOT_PATH . 'public/' . $params['settlement'];
        Log::error($orderSheetsPath);
        Log::error($orderSettlementSheetsPath);

        $spreadsheet = IOFactory::load($orderSheetsPath);
        //$spreadsheet->getSheet()
        $worksheet = $spreadsheet->getActiveSheet();
        $highestRow = $worksheet->getHighestRow(); // 总行数
        Log::error($highestRow);

        $highestColumn = $worksheet->getHighestColumn(); // 总列数
        $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5
        $datas = [];
        for ($row = 3; $row <= $highestRow; ++$row) {
            $skuId = $worksheet->getCell('G' . $row)->getValue(); //SKUID
            //种总的品使用下面的代码
/*            if (empty($skuId[0]) || $skuId[0] != 'P') {
                continue;
            }*/
            $orderId = $worksheet->getCell('A' . $row)->getValue(); //订单ID
            $quantity = $worksheet->getCell('J' . $row)->getValue(); //数量
            $orderStatus = $worksheet->getCell('B' . $row)->getValue(); //订单状态
            $sellPrice = $worksheet->getCell('P' . $row)->getValue(); //商品卖价
            $orderAmount = $worksheet->getCell('W' . $row)->getValue(); //订单总额
            $createAt = $worksheet->getCell('Y' . $row)->getValue(); //创建时间
            $paidAt = $worksheet->getCell('Z' . $row)->getValue(); //支付时间
            $cancelledAt = $worksheet->getCell('AD' . $row)->getValue(); //取消时间
            $cancelReason = $worksheet->getCell('AF' . $row)->getValue(); //取消理由
            $warehouseNameO = $worksheet->getCell('AH' . $row)->getValue(); //仓库发货地址
            $warehouseName = strstr($warehouseNameO, 'Chinese') ? '国内' : $warehouseNameO;

            $deliveryType = $worksheet->getCell('AJ' . $row)->getValue(); //发货类型
            $datas[] = ['orderId' => strval($orderId),
                'orderStatus' => $orderStatus,
                'skuId' => $skuId,
                'quantity' => $quantity,
                'sellPrice' => $region == 1 ? intval(str_replace('.', '', $sellPrice)) : $sellPrice,//越南盾取整
                'orderAmount' => $region == 1 ? intval(str_replace('.', '', $orderAmount)) : $orderAmount,//越南盾取整
                'createAt' => $createAt,
                'paidAt' => $paidAt,
                'cancelledAt' => $cancelledAt,
                'cancelReason' => $cancelReason,
                'warehouseName' => $warehouseName,
                'deliveryType' => $deliveryType,
                'totalSettlementAmount' => '0',
                'sellerShippingFee' => '0',
                'transactionFee' => '0',
                'tkCommissionFee' => '0',
                'SPFServiceFee' => '0',
                'SSTFee' => '0',
                'BonusCashbackServiceFee' => '0',
                'VoucherXtraServiceFee' => '0',
                'AffiliateCommission' => '0',
            ];
        }

        $orderIndexByOrderId = array_column($datas, null, 'orderId');

        //结算单元数据
        $settlementSheet = IOFactory::load($orderSettlementSheetsPath);
        $worksheetSettlement = $settlementSheet->getActiveSheet();
        $highestRowSettlement = $worksheetSettlement->getHighestRow(); // 总行数
        //$highestColumnSettlement = $worksheet->getHighestColumn(); // 总列数
        //var_dump($highestRowSettlement);die();
        for ($i = 2; $i <= $highestRowSettlement; ++$i) {
/*            if ($region == 1) {
                $orderIdS = strval($worksheetSettlement->getCell('AL' . $i)->getValue()); //订单ID
            } elseif ($region == 2 || $region == 3) {
                $orderIdS = strval($worksheetSettlement->getCell('E' . $i)->getValue()); //订单ID
            } else {
                continue;
            }*/
            $orderIdS = strval($worksheetSettlement->getCell('E' . $i)->getValue()); //订单ID
            //var_dump($orderIndexByOrderId);
            if (isset($orderIndexByOrderId[$orderIdS])) {
                $orderIndexByOrderId[$orderIdS]['totalSettlementAmount'] = $worksheetSettlement->getCell('J' . $i)->getValue(); //总结算金额
                //var_dump( $orderIndexByOrderId[$orderIdS]['totalSettlementAmount']);die();
                $orderIndexByOrderId[$orderIdS]['sellerShippingFee'] = $worksheetSettlement->getCell('U' . $i)->getValue(); //卖家实际支付运费
                $orderIndexByOrderId[$orderIdS]['transactionFee'] = $worksheetSettlement->getCell('S' . $i)->getValue(); //平台交易手续费
                $orderIndexByOrderId[$orderIdS]['tkCommissionFee'] = $worksheetSettlement->getCell('T' . $i)->getValue(); //平台佣金
                $orderIndexByOrderId[$orderIdS]['SPFServiceFee'] = $worksheetSettlement->getCell('AE' . $i)->getValue(); //SFP服务费
                $orderIndexByOrderId[$orderIdS]['SSTFee'] = $worksheetSettlement->getCell('AF' . $i)->getValue(); //增值税(SST)
                $orderIndexByOrderId[$orderIdS]['BonusCashbackServiceFee'] = $worksheetSettlement->getCell('AJ' . $i)->getValue(); //奖金返现服务费
                $orderIndexByOrderId[$orderIdS]['VoucherXtraServiceFee'] = $worksheetSettlement->getCell('AH' . $i)->getValue(); //超级优惠券服务费
                $orderIndexByOrderId[$orderIdS]['AffiliateCommission '] = $worksheetSettlement->getCell('AB' . $i)->getValue(); //联盟佣金
                /*                $orderIndexByOrderId[$orderIdS]['totalSettlementAmount'] = $totalSettlementAmount;//总结算金额
                                $orderIndexByOrderId[$orderIdS]['sellerShippingFee'] = $sellerShippingFee;//卖家实际支付运费
                                $orderIndexByOrderId[$orderIdS]['transactionFee'] = $transactionFee;//平台交易手续费
                                $orderIndexByOrderId[$orderIdS]['tkCommissionFee'] = $tkCommissionFee;*/
            }
        }


        //加载最终数据表格模板
        $orderSts = ROOT_PATH . 'public/template/settlementlist.xlsx';
        $orderStsSheet = IOFactory::load($orderSts);
        $worksheetWrite = $orderStsSheet->getActiveSheet();
        $from = 1;

        foreach ($orderIndexByOrderId as $key => $datum) {
            $from += 1;
            $worksheetWrite->getCell('A' . $from)->setValue($shopFlag);
            $worksheetWrite->getCell('B' . $from)->setValue("'" . $datum['orderId']);
            $worksheetWrite->getCell('C' . $from)->setValue($datum['skuId']);
            $worksheetWrite->getCell('G' . $from)->setValue($datum['quantity']);
            $worksheetWrite->getCell('E' . $from)->setValue($datum['orderStatus']);
            $worksheetWrite->getCell('F' . $from)->setValue($datum['sellPrice']);
            $worksheetWrite->getCell('H' . $from)->setValue($datum['orderAmount']);
            $worksheetWrite->getCell('I' . $from)->setValue($datum['createAt']);
            $worksheetWrite->getCell('J' . $from)->setValue($datum['warehouseName']);
            $worksheetWrite->getCell('K' . $from)->setValue($datum['cancelledAt']);
            $worksheetWrite->getCell('L' . $from)->setValue($datum['cancelReason']);
            $worksheetWrite->getCell('M' . $from)->setValue($datum['totalSettlementAmount']);
            $worksheetWrite->getCell('N' . $from)->setValue($datum['sellerShippingFee']);
            $worksheetWrite->getCell('O' . $from)->setValue($datum['transactionFee']);
            $worksheetWrite->getCell('P' . $from)->setValue($datum['tkCommissionFee']);
            $worksheetWrite->getCell('Q' . $from)->setValue($datum['SPFServiceFee']);
            $worksheetWrite->getCell('R' . $from)->setValue($datum['SSTFee']);
            $worksheetWrite->getCell('S' . $from)->setValue($datum['BonusCashbackServiceFee']);
            $worksheetWrite->getCell('T' . $from)->setValue($datum['VoucherXtraServiceFee']);
            $worksheetWrite->getCell('U' . $from)->setValue($datum['AffiliateCommission']);
        }

        $writer = IOFactory::createWriter($orderStsSheet, 'Xlsx');
        $filename = uniqid() . '.xlsx';
        $file_path = ROOT_PATH . 'public/uploads/'.$filename;
        //$writer->save($filename);
        $writer->save($file_path);

        $rs = Request::instance();
        $url = $rs->domain();


        $this->success('成功,请点击弹窗中的链接下载','', ['link'=>$url.'/uploads/'.$filename]);
    }


}
